#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/weixin/get_token.py
# Compiled at: 2017-11-16 15:44:28
import json
from esb.bkcore.models import ESBChannel
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, DefaultBooleanField
from common.constants import API_TYPE_Q
from common.errors import CommonAPIError
from .toolkit import configs

class GetToken(Component, SetupConfMixin):
    """"""
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_Q

    class Form(BaseComponentForm):
        need_new_token = DefaultBooleanField(label=u'是否获取新Token', default=False, required=False)

    def get_wx_config(self):
        try:
            send_weixin_channel = ESBChannel.objects.get(path='/cmsi/send_weixin/')
        except:
            raise CommonAPIError(u'路径为 [/cmsi/send_weixin/] 的通道不存在，无法获取微信配置')

        return dict(json.loads(send_weixin_channel.comp_conf))

    def handle(self):
        wx_config = self.get_wx_config()
        wx_type = wx_config.get('wx_type')
        if wx_type in ('qy', 'qywx'):
            wx_qy_corpid = wx_config.get('wx_qy_corpid')
            wx_qy_corpsecret = wx_config.get('wx_qy_corpsecret')
            if not (wx_qy_corpid and wx_qy_corpsecret):
                raise CommonAPIError(u'请在ESB通道管理中，完善组件 [/cmsi/send_weixin/] 的组件配置')
            kwargs = {'corpid': wx_qy_corpid,'corpsecret': wx_qy_corpsecret
               }
            self.response.payload = self.invoke_other('generic.weixin_qy.get_token', kwargs=kwargs)
        else:
            if wx_type in ('mp', ):
                wx_app_id = wx_config.get('wx_app_id')
                wx_secret = wx_config.get('wx_secret')
                if not (wx_app_id and wx_secret):
                    raise CommonAPIError(u'请在ESB通道管理中，完善组件 [/cmsi/send_weixin/] 的组件配置')
                kwargs = {'appid': wx_app_id,'secret': wx_secret,
                   'need_new_token': self.form_data['need_new_token']
                   }
                self.response.payload = self.invoke_other('generic.weixin_mp.get_token', kwargs=kwargs)
            else:
                self.response.payload = {'result': False,'message': u'组件 [/cmsi/send_weixin/] 的组件配置中，wx_type 的值不在可选范围'}
